// import { useState } from 'react'
export async function getAudio(input: string) {
    // const [status, setStatus] = useState('ready')
    // const [audioUrl, setAudioUrl] = useState('')
    let audioUrl = ''
    const token = import.meta.env.VITE_ACCESS_TOKEN
    const APP_ID = import.meta.env.VITE_APP_ID
    const APP_KEY = import.meta.env.VITE_SECRET_KEY
    // 修改前
    const entPoint = '/tts/api/v1/tts';

    // 修改后
    // 直接使用完整URL，避免依赖代理配置
    // const entPoint = 'https://openspeech.bytedance.com/api/v1/tts';
    const Header = {
        "Authorization": `Bearer;${token}`,
        'Content-Type': 'application/json'
    }
    const payload = {
        "app": {
            "appid": APP_ID,
            "token": APP_KEY,
            "cluster": "volcano_tts",
        },
        "user": {
            "uid": "uid123"
        },
        "audio": {
            "voice_type": "zh_male_junlangnanyou_emo_v2_mars_bigtts",
            "emotion": "tender",
            "encoding": "ogg_opus",
            "speed_ratio": 1.0,
            "volume_ratio": 1.0,
            "pitch_ratio": 1.0,
        },
        "request": {
            "reqid": Date.now(),
            "text": input,
            "operation": "query",
        }
    }
    // setStatus('生成中...')
    // const res = await fetch(entPoint, {
    //     method: 'POST',
    //     headers: Header,
    //     body: JSON.stringify(payload),
    //     credentials: 'include'  // 添加credentials选项
    // })
    const res = await fetch('http://localhost:3000/getAudio', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            text: input
        })
    })
    const data = await res.json()
    console.log(data);
    // 解析并播放音频
    function createBlobUrl(base64AudioData: string) {
        let byteArrays = []
        // 将base64字符串转换为二进制数据
        let byteCharacters = atob(base64AudioData)
        // 遍历每个字符，将其转换为字节
        for (let offset = 0; offset < byteCharacters.length; offset++) {
            let byteArray = byteCharacters.charCodeAt(offset)
            byteArrays.push(byteArray)
        }
        // 将字节数组转换为Blob对象
        let blob = new Blob([new Uint8Array(byteArrays)], { type: 'audio/mp3' })
        // console.log(URL.createObjectURL(blob));

        return URL.createObjectURL(blob)

    }
    // 生成音频URL
    audioUrl = createBlobUrl(data.data)
    // setAudioUrl(createBlobUrl(data.data))
    return audioUrl
}
